# -*- coding: utf-8 -*

__author__ = 'huangxiaoli'

'''
    监控服务器状态 存入mysql
    监控指标：
        host
        time
        load avg
        memTotal
        memUsage
        memFree
'''
import logging
import socket
import time
import mysql.connector
from conf import config, config_default, config_override

class mon:

    def getTime(self):
        return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))

    def getHost(self):
        return socket.gethostname()

    def getLoadAvg(self):
        with open('/proc/loadavg') as load_open:
            a = load_open.read().split()[:3]
            return ','.join(a)

    def getMem(self):
        with open('/proc/meminfo') as mem_open:
            T = int(mem_open.readline().split()[1])
            F = int(mem_open.readline().split()[1])
            A = int(mem_open.readline().split()[1])
            B = int(mem_open.readline().split()[1])
            C = int(mem_open.readline().split()[1])
            return (T,F,A,B,C)

if __name__ == "__main__":
    # 日志文件配置
    logger = logging.getLogger('mylogger')
    formatter = logging.Formatter('%(asctime)s %(levelname)-8s: %(message)s')
    fh = logging.FileHandler('logging.log')
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    logger.setLevel(logging.INFO)

    logger.info('**服务器监控程序启动**')

    configs = config_default.configs
    try:
        configs = config.merge(configs, config_override.configs)
    except ImportError:
        # 日志记录
        logger.info('**import模块报错，请检测配置文件**')
        pass

    host=configs['db']['host']
    port=configs['db']['port']
    dtbase=configs['db']['dtbase']
    username=configs['db']['username']
    password=configs['db']['password']
    charset = configs['db']['charset']

    conn = mysql.connector.connect(host=host,port=port,database=dtbase,user=username, password=password,charset=charset)
    cursor = conn.cursor()
    m = mon()

    while True:
        moniDt=[m.getHost(), m.getTime(),m.getLoadAvg(),m.getMem()[0],m.getMem()[1],m.getMem()[2],m.getMem()[3],m.getMem()[4]]
        try:
            cursor.execute('insert into idc_stat (`host`, `time`,`load_avg`,`mem_total`,`mem_free`,`mem_available`,`mem_buffers`,`mem_cached`) values (%s, %s, %s, %s, %s, %s, %s, %s)', moniDt)
            conn.commit()
        except mysql.IntegrityError:
            # 日志记录
            logger.info('**Insert模块报错，数据插入失败**')
            pass
        # 线程沉睡
        time.sleep(5)
    cursor.close()
    conn.close()
    logger.removeHandler(fh)